package com.zp.self.module.工具.rpc远程访问.restTemplate;

import com.zp.self.module.简单的login.Person;
import org.junit.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ：byH
 * @date ：Created 2022/1/16 14:50
 * @description： RestTemplate 的使用方法
 * 参考：https://zhuanlan.zhihu.com/p/31681913
 *      https://blog.csdn.net/u011138533/article/details/87920632
 *
 * 重点：
 * 1.getForObject 函数实际上是对 getForEntity 函数的进一步封装，postForObject同理
 * 2.postForEntity  第二个参数是请求体
 * 3.请求头
 * 4.返回值乱码:restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
 * 5.url 后面的参数可以占位符拼接
 * A.getForEntity("http://HELLO-SERVICE/sayhello?name={1}", String.class, "张三");
 * B.getForEntity("http://HELLO-SERVICE/sayhello?name={name}", String.class, map);
 */
public class RemoteProcedureCallService {

    /**
    *  get请求
    **/
    @Test
    public void getRPC(){
        RestTemplate restTemplate = new RestTemplate();
        //1.常规请求
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://127.0.0.1:8800/date/get"
//              , String.class, "didi");
        ResponseEntity<Person> responseEntity = restTemplate.getForEntity("http://127.0.0.1:8800/date/get?name={1}"
                , Person.class, "大表哥");

        // 2、使用postForEntity请求接口
        //请求头设备
        HttpHeaders headers  = new HttpHeaders();
        headers.set("token", UUID.randomUUID().toString());
        //body参数map
        Map<String,String> map = new HashMap<>();
        map.put("name","麻子");
        HttpEntity<Map<String,String>> httpEntity = new HttpEntity<>(map,headers);

        String url = "http://127.0.0.1:8800/date/get";
        ResponseEntity<String> response2 = restTemplate.postForEntity(url, httpEntity, String.class);

        // 3、使用exchange请求接口
        ResponseEntity<String> response3 = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        Person body = responseEntity.getBody();
        System.out.println(body);
        Assert.notNull(body,"为空了？");
    }


}
